package com.xywh.wanandroid.compose_ui.search

import android.app.Activity
import android.text.Html
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.consumeWindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FabPosition
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ListItem
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.xywh.composeLibrary.ext.ListFloatingActionButton
import com.xywh.composeLibrary.statex.PageState
import com.xywh.composeLibrary.statex.StateCompose
import com.xywh.wanandroid.data.model.bean.ArticleItem
import com.xywh.wanandroid.event.EventViewModel.Companion.isLogin
import com.xywh.wanandroid.ext.hideSoftKeyboard
import com.xywh.wanandroid.ext.showToastMsg
import com.xywh.wanandroid.viewmodel.SearchComposeViewModel

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchScreen(
    listState: LazyListState = rememberLazyListState(),
    viewModel: SearchComposeViewModel = hiltViewModel(),
    updateMainScreenCollectListData: () -> Unit,
    navigateUp: () -> Unit,
    navigateWebView: (String, String) -> Unit,
) {
    val scope = rememberCoroutineScope()
    val activity = LocalContext.current as Activity

    var key by rememberSaveable { mutableStateOf("") }
    val contentState = remember {
        PageState(PageState.empty("暂无数据"))
    }


    Scaffold(
        topBar = {
            TopAppBar(
                title = {

                    Box(
                        modifier = Modifier
                            .fillMaxSize(),
                        contentAlignment = Alignment.Center
                    ) {
                        BasicTextField(
                            cursorBrush = SolidColor(Color.Red),
                            value = key,
                            onValueChange = {
                                key = it
                            },
                            modifier = Modifier
                                .background(Color.White, RoundedCornerShape(10))
                                .height(35.dp)
                                .fillMaxWidth(),
                            decorationBox = { innerTextField ->

                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    modifier = Modifier
                                        .padding(start = 10.dp)
                                        .fillMaxWidth()

                                ) {

                                    Box(
                                        modifier = Modifier.weight(3f),
                                        contentAlignment = Alignment.CenterStart
                                    ) {
                                        if (key.isEmpty()) Text(
                                            "请输入关键字",
                                            style = LocalTextStyle.current.copy(
                                                color = Color.Gray,
                                                fontSize = 12.sp
                                            )
                                        )
                                        innerTextField()
                                    }
                                    IconButton(
                                        onClick = { key = "" },
                                    ) {
                                        if (key.isNotEmpty()) {
                                            Icon(
                                                Icons.Filled.Clear,
                                                modifier = Modifier.size(14.dp),
                                                contentDescription = "Localized description",
                                            )
                                        }

                                    }
                                }
                            }
                        )
                    }

                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary
                ),
                navigationIcon = {
                    IconButton(
                        onClick = { navigateUp.invoke() }
                    ) {
                        Icon(
                            Icons.Filled.ArrowBack,
                            contentDescription = "Localized description",
                            tint = Color.White
                        )
                    }
                },
                actions = {
                    IconButton(onClick = {
                        if (key.isEmpty()) {
                            showToastMsg("请输入关键字")
                            return@IconButton
                        }
                        hideSoftKeyboard(activity)
                        contentState.changeState(PageState.loading())
                        viewModel.articleList.value = null
                        viewModel.queryBySearchKey(key)
                    }) {
                        Icon(
                            Icons.Filled.Search,
                            contentDescription = "Search",
                            tint = Color.White
                        )
                    }
                },
            )
        },
        floatingActionButtonPosition = FabPosition.End,
        floatingActionButton = {

            ListFloatingActionButton(scope, listState)
        },
        content = { innerPadding ->

            val articles = viewModel.articleList.value?.collectAsLazyPagingItems()

            articles?.let {
                if (key.isNotEmpty() && articles.itemCount > 0) {
                    contentState.changeState(PageState.success(""))
                }
            }

            StateCompose(articles, contentState) {
                SearchContent(
                    listState,
                    innerPadding,
                    articles,
                    navigateWebView = navigateWebView,
                    favoriteOnClick = { id, collect ->
                        if (collect) {
                            viewModel.cancelCollectArticle(
                                id,
                                updateMainScreenCollectListData
                            )
                        } else {
                            viewModel.addCollectArticle(
                                id,
                                updateMainScreenCollectListData
                            )
                        }
                    }
                )
            }


        }

    )
}


@Composable
fun SearchContent(
    listState: LazyListState,
    innerPadding: PaddingValues,
    articles: LazyPagingItems<ArticleItem>?,
    navigateWebView: (String, String) -> Unit,
    favoriteOnClick: (Int, Boolean) -> Unit
) {


    LazyColumn(
        state = listState,
        // consume insets as scaffold doesn't do it by default
        modifier = Modifier
            .consumeWindowInsets(innerPadding),
        contentPadding = innerPadding,
    ) {

        articles?.let {

            items(
                count = articles.itemCount,
                key = { index ->
                    val article = articles[index]
                    "${article?.id ?: ""}${index}"
                }) {
                val itemData = articles[it] ?: return@items
                SearchArticleItem(
                    itemData,
                    false,
                    favoriteOnClick = favoriteOnClick
                ) { title, link ->
                    navigateWebView.invoke(title, link)
                }
            }
        }

    }
}


@Composable
fun SearchArticleItem(
    itemArticle: ArticleItem,
    isTop: Boolean,
    favoriteOnClick: (Int, Boolean) -> Unit,
    itemOnClick: (title: String, link: String) -> Unit
) {
    ListItem(
        modifier = Modifier.clickable {
            itemOnClick.invoke(itemArticle.title, itemArticle.link)
        },
        headlineContent = {
            Text(
                Html.fromHtml(itemArticle.title).toString(),
                fontSize = 14.sp,
                color = Color.Black,
                modifier = Modifier
                    .padding(top = 10.dp)
                    .fillMaxWidth(),
            )
        },
        overlineContent = {
            Row(Modifier.fillMaxWidth()) {

                if (isTop) {
                    Text(
                        "置顶",
                        fontSize = 10.sp,
                        color = Color(0xFFF44336),
                        modifier = Modifier
                            .padding(end = 5.dp)
                            .border(
                                0.5.dp,
                                color = Color(0xFFF44336),
                                shape = RoundedCornerShape(10)
                            )
                            .padding(5.dp, 2.dp)
                    )
                }
                if (itemArticle.fresh) {
                    Text(
                        "新",
                        fontSize = 10.sp,
                        color = Color(0xFFF44336),
                        modifier = Modifier
                            .padding(end = 5.dp)
                            .border(
                                0.5.dp,
                                color = Color(0xFFF44336),
                                shape = RoundedCornerShape(10)
                            )
                            .padding(5.dp, 2.dp)
                    )
                }
                if (!itemArticle.tags.isNullOrEmpty()) {
                    Text(
                        itemArticle?.tags[0].name,
                        fontSize = 10.sp,
                        color = Color(0xFF37CADD),
                        modifier = Modifier
                            .padding(end = 5.dp)
                            .border(
                                0.5.dp,
                                color = Color(0xFF37CADD),
                                shape = RoundedCornerShape(10)
                            )
                            .padding(5.dp, 2.dp)
                    )
                }
                Text(
                    itemArticle.author.ifEmpty { itemArticle.shareUser },
                    fontSize = 10.sp,
                    color = Color(0xFF747474),
                    modifier = Modifier
                        .align(Alignment.Bottom)
                )

                Text(
                    itemArticle.niceDate ?: "",
                    fontSize = 10.sp,
                    color = Color(0xFF747474),
                    modifier = Modifier
                        .padding(start = 5.dp)
                        .fillMaxWidth()
                        .align(Alignment.Bottom),
                    textAlign = TextAlign.End
                )
            }
        },
        supportingContent = {


            Row(
                Modifier
                    .padding(top = 10.dp)
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {

                Text(
                    "${itemArticle.superChapterName ?: ""}/${itemArticle.chapterName ?: ""}",
                    fontSize = 12.sp,
                    color = Color(0xFF787878)
                )

                var favorite = Icons.Filled.FavoriteBorder

                if (itemArticle.collect) {
                    favorite = Icons.Filled.Favorite
                }
                Icon(
                    favorite,
                    modifier = Modifier
                        .size(18.dp)
                        .clickable {
                            if (isLogin.value) {
                                val collect = itemArticle.collect
                                itemArticle.collect = !itemArticle.collect
                                favoriteOnClick.invoke(itemArticle.id, collect)
                            } else {
                                showToastMsg("请先登录")
                            }

                        },
                    contentDescription = "Localized description",
                )
            }
        },
        //                        leadingContent = {
        //
        //                        },
        //                        trailingContent = {
        //
        //                        }
    )
    Divider()
}
